package com.mrd.gtimp.business.action;

import static com.mrd.util.AdminUtil.checkRight;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SpecialConstant;
import com.mrd.constant.SystemConstants;
import com.mrd.evaluate.service.EvaluationBiz;
import com.mrd.exception.FeeException;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.business.entity.ContractTerms;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.DeclarationFree;
import com.mrd.gtimp.business.entity.DeclarationFreeDetail;
import com.mrd.gtimp.business.entity.InspectionGoods;
import com.mrd.gtimp.business.repository.CargoDeclaRecordDao;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.mrd.gtimp.business.service.ContractTermsBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.DeclarationFreeBiz;
import com.mrd.gtimp.business.service.DeclarationFreeDetailBiz;
import com.mrd.gtimp.business.service.FundFlowBiz;
import com.mrd.gtimp.business.service.HongbaoBiz;
import com.mrd.gtimp.business.service.InspectionGoodsBiz;
import com.mrd.gtimp.business.service.PackingListDetailedBiz;
import com.mrd.gtimp.order.action.OrderAction;
import com.mrd.gtimp.service.client.CtmsServiceClient;
import com.mrd.gtimp.service.client.SupBizServiceClient;
import com.mrd.gtimp.service.dto.CTMSShipInfoDTO;
import com.mrd.gtimp.service.dto.SupBaseBizQueryDTO;
import com.mrd.gtimp.v2.datalock.DataLockUtil;
import com.mrd.gtimpframe.entity.ComDeclaWay;
import com.mrd.gtimpframe.service.ChargingService;
import com.mrd.gtimpframe.service.CompanyService;
import com.mrd.gtimpframe.service.DeclarationService;
import com.mrd.gtimpframe.singlewindow.SingleWindow;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.KeyGenerator;
import com.mrd.util.LoginUtil;
import com.mrd.util.ReflectUtil;
import com.mrd.util.ZipUtil;

import net.sf.json.JSONObject;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class DeclarationAction {

    private static final long serialVersionUID = 1L;
    @Resource
    private DeclarationBiz declarationBiz;
    @Resource
    private DeclarationFreeBiz declarationFreeBiz;
    @Resource
    private DeclarationFreeDetailBiz declarationFreeDetailBiz;
    @Resource
    private PackingListDetailedBiz packingListDetailedBiz;
    @Resource
    private AttachmentBiz attachmentBiz;
    @Resource
    private DeclarationService declarationService;
    @Resource
    private CompanyService companyService;
    @Resource
    private DataLockUtil dataLockUtil;
    /**
     * 结算所需的报关单信息
     */
    // private String pay_id;
    // private List<String> clearance_ids; // 需要报检的报关单id
    // private List<String> steaming_ids; // 需要熏蒸的报关单id
    private List<String> mmf_ids_ids; // 需要报市场购买家私的报关单id
    // private String sum_free;
    // private List<DeclarationFree> declarationFrees;
    private String payment_Type; // 付款类型
    // 0=未付款
    // 1=已付款
    // 2=免费

    private List<String> declaration_ids;
    @Resource
    private HongbaoBiz hongbaoBiz;

    @Resource
    private CargoDeclaRecordDao cargoDeclaRecordDao;

    /**
     * 获取柜号输入的柜号
     */
    // private String container_no;
    /**
     * 获取柜号的类型
     */
    // private String work_type;

    /**
     * 默认访问入口
     *
     * @param companyId 登录用户的公司ID
     */
    @RequestMapping("/declaration-main")
    public String main(String companyId, Model model) {
        companyId = LoginUtil.getLoginUser().getCompany().getId();
        model.addAttribute("companyId", companyId);
        return "/gtimp/declaration/declarationlist";
    }

    /**
     * 报关单驳回列表入口
     *
     * @param companyId 登录用户的公司ID
     */
    @RequestMapping("/declaration-rejectMain")
    public String rejectMain(String companyId, Model model) {
        companyId = LoginUtil.getLoginUser().getCompany().getId();
        model.addAttribute("companyId", companyId);
        return "/gtimp/declaration/declarationRejectlist";
    }

    /**
     * 客户详细报表入口
     */
    @RequestMapping("/declaration-customerReportMain")
    public String customerReportMain(String companyId, Model model) {
        companyId = LoginUtil.getLoginUser().getCompany().getId();
        model.addAttribute("companyId", companyId);
        return "/gtimp/declaration/customerDeclarationReportlist";
    }

    /**
     * 供应商详细报表入口
     */
    @RequestMapping("/declaration-supReportMain")
    public String supReportMain(String companyId, Model model) {
        companyId = LoginUtil.getLoginUser().getCompany().getId();
        model.addAttribute("companyId", companyId);
        return "/gtimp/declaration/supDeclarationReportList";
    }

    /**
     * 平台详细报表入口
     */
    @RequestMapping("/declaration-platFormReportMain")
    public String platFormReportMain(String companyId, Model model) {
        companyId = LoginUtil.getLoginUser().getCompany().getId();
        model.addAttribute("companyId", companyId);
        return "/gtimp/declaration/platFormDeclarationReportList";
    }

    /**
     * 模版列表
     */
    @RequestMapping("/declaration-model")
    public String model() {
        return "model";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/declaration-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 导出报关资料入口
     */
    @RequestMapping("/declaration-exportDeclaration")
    public String exportDeclaration() {
        return "/gtimp/declaration/exportDeclaration";
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/declaration-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(Declaration declaration) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(declaration.getId())) { // 新增操作
                    // declaration.setCOM_ID(LoginUtil.getLoginUser().getCompany().getId());
                    // declaration.setCREATOR(LoginUtil.getLoginUser().getAccount());
                    // declaration.setCTIME(new Date());
                    declaration.setId(null);
                } else { // 修改操作
                    // declaration.setMODIFIER(LoginUtil.getLoginUser().getAccount());
                    // declaration.setMTIME(new Date());
                }
                if (jedisClientCluster.get("lock_decla_" + declaration.getId(), String.class) != null) {
                    return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
                }
                declarationBiz.saveOrupdateEntity(declaration);
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/declaration-find")
    @ResponseBody
    @Json({@JField("id"), @JField("sno"), @JField("data_type"), @JField("ship_name"), @JField("export_port"), @JField("voyage_no"), @JField("bl_no"), @JField("transport_na"), @JField("ship_code")})
    public Declaration find(Declaration declaration, @RequestParam(required = false) String isSignWS) {
        if (declaration != null && StringUtils.isNotEmpty(declaration.getId())) {
            try {
                declaration = declarationBiz.findEntityById(declaration.getId());
                if (StringUtils.isNotEmpty(isSignWS) && isSignWS.equalsIgnoreCase("true")) {
                    CTMSShipInfoDTO dto = declarationBiz.getShipInfo(declaration.getId());
                    if (dto != null) {
                        // if(StringUtils.isNotEmpty(dto.getBlNo())){
                        // declaration.setData_type("直航");
                        // }else{
                        // declaration.setData_type("转关");
                        // }
                        declaration.setShip_name(dto.getShipName());// 船名
                        declaration.setShip_code(dto.getShipCode());// 船舶代码
                        //            declaration.setExport_port(dto.getePort());// 出口口岸
                        if ("直航".equals(declaration.getData_type())) {
                            declaration.setTransport_na(dto.getShipCode());// 运输工具名称
                        }
                        declaration.setVoyage_no(dto.getVoyageNo());// 航次号
                        declaration.setBl_no(dto.getBlNo());// 提运单号
                    }
                }
                return declaration;
            } catch (QueryException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 删除信息
     */
    @RequestMapping("/declaration-del")
    @ResponseBody
    public Result del() {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                // String ids = HttpUtils.getParam("id");
                // String[] idArr = ids.split(",");
                // StringBuffer sb = new StringBuffer();
                // for(String string : idArr) {
                // sb.append("'").append(string).append("',");
                // }
                // if(sb.length() > 0) {
                // sb.deleteCharAt(sb.length() - 1);
                // filters = new Filter();
                // filters.setGroupOp(FilterGroupOption.AND);
                // filters.addRule(new SearchRule("ID", SearchRuleOption.in, sb.toString()));
                // declarationBiz.deleteByFilter(filters);
                // }
                String ids = HttpUtils.getParam("id");
                if (jedisClientCluster.get("lock_decla_" + ids, String.class) != null) {
                    return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
                }
                Declaration d = new Declaration();
                d.setId(ids);
                declarationBiz.delete(d);
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    @Resource
    public void setDeclarationBiz(DeclarationBiz declarationBiz) {
        this.declarationBiz = declarationBiz;
    }

    /**
     * 供应商业务审核列表页面(已提交待审核)
     */
    @RequestMapping("/declaration-listForSupToValidate")
    public String listForSupToValidate() {
        return "/gtimp/declaration/declarationlistForSupToValidate";
    }

    /**
     * 供应商业务审核列表页面(已受理)
     */
    @RequestMapping("/declaration-acceptedListForSupToValidate")
    public String acceptedListForSupToValidate() {
        return "/gtimp/declaration/declarationAcceptedListForSupToValidate";
    }

    /**
     * 供应商业务审核列表页面(驳回)
     */
    @RequestMapping("/declaration-rejectListForSupToValidate")
    public String rejectListForSupToValidate() {
        return "/gtimp/declaration/declarationRejectListForSupToValidate";
    }

    /**
     * 查询列表给供应商审核业务信息
     *
     * @param declaraState 报关列表状态
     */
    @RequestMapping("/declaration-findListForSupToValidate")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("workNo"), @JField("container_no"), @JField("contract_no"), @JField("company_name"), @JField("customer.name"), @JField("shipper.company"), @JField("confirmTime"), @JField("decState"), @JField("validator.name"), @JField("validateTime"), @JField("declarationInform.confirmState"), @JField("realSupId"), @JField("re_manifest")})
    public Page<Declaration> findListForSupToValidate(String declaraState, Jqgrid jqgrid) {
        Filter filters = jqgrid.getFilters();
        List<Declaration> declarations = new ArrayList<>();
        String comId = LoginUtil.getLoginUser().getCompany().getId();// 此处为供应商
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            //// TODO: 2016/9/1 filters
            SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            // SearchRule rule2 = new SearchRule("state", SearchRuleOption.nc,
            // BaseTypeConstant.DECLARATIONSTATE_00);
            // filters.addRule(rule2);
            declaraState = declaraState.substring(0, 4);
            if ("DS01".equals(declaraState)) {// 已下单待审核
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.eq, BaseTypeConstant.DECLARATIONSTATE_01);
                filters.addRule(rule2);
            } else if ("DS03".equals(declaraState)) {// 驳回
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.eq, BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            } else {// 通过审核，已受理
                // SearchRule rule2 = new SearchRule("state", SearchRuleOption.in,
                // BaseTypeConstant.DECLARATIONSTATE_02
                // + "," + BaseTypeConstant.DECLARATIONSTATE_04);
                // filters.addRule(rule2);
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.nc, BaseTypeConstant.DECLARATIONSTATE_00 + "," + BaseTypeConstant.DECLARATIONSTATE_01 + "," + BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            }
            // page = initPage(declarationBiz.findEntityCount(filters));
            // Order order = new Order();
            // if (null != sidx && !"".equals(sidx)) {
            // order.add(sidx, sord);
            // }
            String listCase = "select sval.chn, declaration from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval where declaration.state=sval.identifier  and (1=1 ";
            String listCaseCount = "select count(*) from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval where declaration.state=sval.identifier  and (1=1 ";
            String whereCase = "";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (sr.getOp() == SearchRuleOption.eq) {
                        if (data.equals("DS04")) {
                            whereCase = whereCase + " and declaration." + field + " in('DS04','DS06','DS07','DS08')";
                        } else {
                            whereCase = whereCase + " and declaration." + field + " = '" + data + "' ";
                        }
                    }
                }
            }
            // 业务流转查询
            whereCase = whereCase + " or declaration.id in (select bf.bizId from com.mrd.gtimp.business.entity.BizFlow bf where bf.scompany='" + comId + "' or bf.tcompany='" + comId + "')) ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Declaration.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            if (sr.getOp().equals(SearchRuleOption.lt) || sr.getOp().equals(SearchRuleOption.le)) {
                                data = "to_date('" + data + " 23:59:59','yyyy-MM-dd hh24:mi:ss')";
                            } else {
                                data = "to_date('" + data + "','yyyy-MM-dd')";
                            }
                            isDate = true;
                        }
                    }
                    if (!"supCompany.id".equals(field) && !data.equals(BaseTypeConstant.DECLARATIONSTATE_00)) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            if (data.equals("DS04")) {
                                whereCase = whereCase + " and declaration." + field + " in('DS04','DS06','DS07','DS08')";
                            } else {
                                whereCase = whereCase + " and declaration." + field + " ='" + data + "' ";
                            }
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'" + "," + "'" + data.toString().substring(10, 14) + "'";
                            whereCase = whereCase + " and declaration." + field + " not in (" + data + ")";
                        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " > " + data : " > '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " < " + data : " < '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " >= " + data : " >= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.le)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " <= " + data : " <= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.in)) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                            whereCase = whereCase + " and declaration." + field + " in(" + data + ")";
                        } else {
                            whereCase = whereCase + " and declaration." + field + " like '%" + data + "%' ";
                        }
                    }
                }
            }
            // for (String key : order.keySet()) {
            // whereCase = whereCase + " order by declaration." + key + " "
            // + (order.get(key) ? "desc" : "asc") + " ";
            // }

            listCase = listCase + whereCase;
            listCaseCount = listCaseCount + whereCase;
            int count = declarationBiz.findEntityCountByHql(listCaseCount, null);
            List<Object> objList = declarationBiz.findObjectByHql(listCase, jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
            if (null != objList && objList.size() > 0) {
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Declaration b = (Declaration) os[1];
                    // b.setDecState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0]
                    // .toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0]
                    // .toString());
                    b.setDecState(os[0].toString());
                    String realSupId = b.getRealSupId();
                    if (StringUtils.isNotEmpty(realSupId)) {
                        if (realSupId.equals(comId)) {
                            b.setRealSupId(realSupId + ":业务流入");
                        } else {
                            b.setRealSupId(realSupId + ":业务流出");
                        }
                    }
                    // add lock state -- luob
                    String regUser = LoginUtil.getLoginUser().getAccount() + LoginUtil.getLoginUser().getName();
                    b.setState(dataLockUtil.tryLockDeclaration(b.getId(), regUser) ? b.getState() : "已锁定");
                    declarations.add(b);
                }
            }
            Page<Declaration> page = new PageImpl<>(declarations, jqgrid.getPage(), count);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 供应商业务审核详细页面
     */
    @RequestMapping("/declaration-findForSupToValidate")
    public String findForSupToValidate(Declaration declaration, Model model) {
        String id = HttpUtils.getParam("id");
        if (StringUtils.isNotEmpty(id)) {
            try {
                declaration = declarationBiz.findEntityById(id);
                model.addAttribute("declaration", declaration);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "/gtimp/declaration/declarationInfoForSupToValidate";
    }

    /**
     * 供应商-已提交待审核 （审核）
     */
    @RequestMapping("/declaration-checkValidatePass")
    @ResponseBody
    public Result checkValidatePass(String id, String opType) {
        Result msg;
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select declaration.state from com.mrd.gtimp.business.entity.Declaration declaration where declaration.id='" + id + "'";
                List<Object> objlist = declarationBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    if ("tgsh".equals(opType) || "bh".equals(opType)) {
                        if (BaseTypeConstant.DECLARATIONSTATE_01.equals(objlist.get(0)) || BaseTypeConstant.DECLARATIONSTATE_02.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    } else {
                        if (BaseTypeConstant.DECLARATIONSTATE_02.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    }
                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else

        {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        return msg;
    }

    public Result checkValidateReject(String id, String optype) {
        return checkValidatePass(id, optype);
    }

    @RequestMapping("/declaration-validatePass")
    @ResponseBody
    public Result validatePass(Declaration declaration) {
        Result msg;
        try {
            if (declaration != null && jedisClientCluster.get("lock_decla_" + declaration.getId(), String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
            String businessId = HttpUtils.getParam("businessId");
            declaration = declarationBiz.findEntityById(declaration.getId());
            String creator = declaration.getCreator();
            // System.out.println("通过审核前此单状态 ===========" + declaration.getDecState());
            // System.out.println("通过审核前此单id ===========" + declaration.getId());
            // System.out.println("通过审核前此单businessId ===========" + businessId);
            // System.out.println("通过审核前此单businessId ===========" + declaration.getBusinessId());
            if (declaration.getDecState().equals(BaseTypeConstant.DECLARATIONSTATE_01)) {
                declarationBiz.updateValidatePass(declaration.getId());
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
                // 发微信红包
                //// TODO: 2016/8/29
                // new App().sendHongBao(new HongBaoTask().setUser_account(creator)
                // .setTemplate_id(WeixinApiConfigUtil.getValue("hongbao.login")).setAmount(1)
                // .setBizids(declaration.getBusinessId()));
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/declaration-validateReject")
    @ResponseBody
    public Result validateReject(Declaration declaration) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            if (declaration != null && jedisClientCluster.get("lock_decla_" + id, String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
            declaration = declarationBiz.findEntityById(id);
            if (declaration.getDecState().equals(BaseTypeConstant.DECLARATIONSTATE_01)) {
                declarationBiz.updateValidateReject(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 其他报关行海关放行
     */
    @RequestMapping("/declaration-customsPassDeclaration")
    @ResponseBody
    public Result customsPassDeclaration() {
        Result msg;
        String id = HttpUtils.getParam("id");
        for (String did : id.split(",")) {
            if (jedisClientCluster.get("lock_decla_" + did, String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
        }
        System.out.println(id);
        try {
            declarationBiz.updateCustomsPassDeclaration(id);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 其他报关行商检放行
     */
    @RequestMapping("/declaration-commodityInspectionPass")
    @ResponseBody
    public Result commodityInspectionPass() {
        Result msg;
        String id = HttpUtils.getParam("id");
        for (String did : id.split(",")) {
            if (jedisClientCluster.get("lock_decla_" + did, String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
        }
        System.out.println(id);
        try {
            declarationBiz.updateCommodityInspectionPass(id);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 其他报关行完成
     */
    @RequestMapping("/declaration-finishDeclarationPass")
    @ResponseBody
    public Result finishDeclarationPass() {
        Result msg;
        String id = HttpUtils.getParam("id");
        for (String did : id.split(",")) {
            if (jedisClientCluster.get("lock_decla_" + did, String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
        }
        System.out.println(id);
        try {
            declarationBiz.updateFinishDeclarationPass(id);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 业务查看入口
     */
    @RequestMapping("/declaration-bizView")
    public String bizView(Declaration declaration, Model model) {
        findForSupToValidate(declaration, model);
        return "/gtimp/declaration/declarationInfoForView";
    }

    /**
     * 业务修改入口
     */
    @RequestMapping("/declaration-bizModify")
    public String bizModify() {
        return "bizModify";
    }

    /**
     * 检查业务是否可以进入修改页面
     */
    @RequestMapping("/declaration-checkBizModify")
    @ResponseBody
    public Result checkBizModify() {
        Result msg;
        String id = HttpUtils.getParam("id");
        if (jedisClientCluster.get("lock_decla_" + id, String.class) != null) {
            return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
        }
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select declaration.state from com.mrd.gtimp.business.entity.Declaration declaration where declaration.id='" + id + "'";
                List<Object> objlist = declarationBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    if (BaseTypeConstant.DECLARATIONSTATE_03.equals(objlist.get(0)) || BaseTypeConstant.DECLARATIONSTATE_00.equals(objlist.get(0))) {
                        msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                    } else {
                        msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                    }
                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        return msg;
    }

    /**
     * 检查业务是否可以进行提交操作
     */
    @RequestMapping("/declaration-checkBizConfirm")
    public Result checkBizConfirm() {
        return checkBizModify();
    }

    /**
     * 业务结算
     */
    @RequestMapping("/declaration-setAccount")
    public String setAccount(String declaration_idStr) {
        List<String> declaration_ids = null;
        List<Declaration> declarations = null;
        ArrayList<DeclarationFreeDetail> declarationFreeDetails = null;
        String flag = "rejectMain";
        try {
            if (declaration_idStr != null && !"".equals(declaration_idStr)) {
                declaration_ids = new ArrayList<String>();
                String[] str = declaration_idStr.split(",");
                for (String s : str) {
                    declaration_ids.add(s);
                }
            }

            String hql = "from com.mrd.gtimp.business.entity.Declaration declaration where declaration.id in (";
            for (String id : declaration_ids) {
                hql += "'" + id + "',";
            }
            hql = hql.substring(0, hql.lastIndexOf(","));
            hql += ")";
            // 获取需要结算的报关单
            List<Object> objectlist = declarationBiz.findObjectByHql(hql, 0, 100, null);
            if (null != objectlist && objectlist.size() > 0) {
                if (declarations == null) {
                    declarations = new ArrayList<Declaration>();
                }
                for (Object o : objectlist) {
                    Declaration b = (Declaration) o;
                    declarations.add(b);
                }
            }
            // 筛选出驳回状态的订单
            List<Declaration> r_declaration = new ArrayList<Declaration>();
            for (Declaration decl : declarations) {
                if (decl.getState() != null && decl.getState().equals(BaseTypeConstant.DECLARATIONSTATE_03)) {
                    declarationBiz.updateBizConfirm(decl.getId());
                    r_declaration.add(decl);
                }
            }
            declarations.removeAll(r_declaration);
            if (declarations.size() > 0) {
                // 获取报关费用项目
                String dhql = "from com.mrd.gtimp.business.entity.DeclarationFreeDetail detail";
                List<Object> dObjectlist = declarationFreeDetailBiz.findObjectByHql(dhql, 0, 100, null);
                if (null != dObjectlist && dObjectlist.size() > 0) {
                    if (declarationFreeDetails == null) {
                        declarationFreeDetails = new ArrayList<DeclarationFreeDetail>();
                    }
                    for (Object o : dObjectlist) {
                        DeclarationFreeDetail b = (DeclarationFreeDetail) o;
                        declarationFreeDetails.add(b);
                    }
                }
                // 计算报关费用
                declarations = declarationFreeBiz.countFree(declarations, declarationFreeDetails);
                flag = "rejectMain";
            }
        } catch (QueryException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Resource
    private FundFlowBiz fundFlowBiz;
    @Resource
    private ChargingService chargingService;

    /**
     * 结算 并 选择支付页面
     *
     * @param ids 修改页面传回报关id
     */
    @RequestMapping("/declaration-confirmPay")
    public String confirmPay(String[] declaration_id, String ids, String payment_Type, String[] steaming_id, String[] clearance_ids) {
        Object[] returns = new Object[0];
        try {
            returns = chargingService.calcDeclarationFee(declaration_id);
            if (returns != null) {
                HttpUtils.getRequest().setAttribute("pay_id", returns[0]);
                HttpUtils.getRequest().setAttribute("sum_free", returns[1]);
                HttpUtils.getRequest().setAttribute("declarations", returns[2]);
            }
            HttpUtils.getRequest().setAttribute("balance", fundFlowBiz.findCurrentBalance(LoginUtil.getLoginUser().getCompany().getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/gtimp/declaration/confirmPay";
    }

    /**
     * 结算 并 选择支付页面
     *
     * @param ids 修改页面传回报关id
     */
    @RequestMapping("/declaration-confirmPay-old")
    public String confirmPayOld(String[] declaration_id, String ids, String payment_Type, String[] steaming_id, String[] clearance_ids) {
        String pay_id;
        String sum_free;
        List<Declaration> declarations = null;
        List<DeclarationFreeDetail> declarationFreeDetails = null;
        List<DeclarationFree> declarationFrees = null;
        // 重新结算报关费
        try {
            String hql = "from com.mrd.gtimp.business.entity.Declaration declaration where declaration.id in (";
            for (String id : declaration_id) {
                hql += "'" + id + "',";
            }
            hql = hql.substring(0, hql.lastIndexOf(","));
            hql += ")";
            // 获取需要结算的报关单
            List<Object> objectlist = declarationBiz.findObjectByHql(hql, 0, 100, null);
            if (null != objectlist && objectlist.size() > 0) {
                declarations = new ArrayList<Declaration>();
                for (Object o : objectlist) {
                    Declaration b = (Declaration) o;
                    declarations.add(b);
                }
            }
            // 获取报关费用项目
            String dhql = "from com.mrd.gtimp.business.entity.DeclarationFreeDetail detail";
            List<Object> dObjectlist = declarationFreeDetailBiz.findObjectByHql(dhql, 0, 50, null);
            if (null != dObjectlist && dObjectlist.size() > 0) {
                declarationFreeDetails = new ArrayList<DeclarationFreeDetail>();
                for (Object o : dObjectlist) {
                    DeclarationFreeDetail b = (DeclarationFreeDetail) o;
                    declarationFreeDetails.add(b);
                }
            }

            // 计算报关费用
            declarations = declarationFreeBiz.countFree(declarations, declarationFreeDetails);
        } catch (QueryException e) {
            e.printStackTrace();
        } catch (FeeException e) {
            declarations = null;
            HttpUtils.getRequest().setAttribute("err", e.getMessage());
        }
        if (declarations != null) {
            HashMap<String, Declaration> declarationMap = new HashMap<String, Declaration>();
            for (Declaration d : declarations) {
                declarationMap.put(d.getId(), d);
            }
            Double sum = new Double(0);
            for (Declaration d : declarations) {
                sum += d.getDeclaration_free();
            }
            // 结算需要报检的报关单
            if (clearance_ids != null && clearance_ids.length > 0) {
                for (String id : clearance_ids) {
                    Declaration d = declarationMap.get(id);
                    Double cFree = countClearanceFree(d);
                    d.setDeclaration_free(d.getDeclaration_free() + cFree);
                    sum += cFree;
                }
            }
            // 结算需要熏蒸的报关单
            if (steaming_id != null && steaming_id.length > 0) {
                for (String id : steaming_id) {
                    Declaration d = declarationMap.get(id);
                    Double sFree = countSteamingFree(d);
                    d.setDeclaration_free(d.getDeclaration_free() + sFree);
                    sum += sFree;
                }
            }
            // 结算需要报市场家私的报关单
            if (mmf_ids_ids != null && mmf_ids_ids.size() > 0) {
                for (String id : mmf_ids_ids) {
                    Declaration d = declarationMap.get(id);
                    Double mFree = countMMFFree(d);
                    d.setDeclaration_free(d.getDeclaration_free() + mFree);
                    sum += mFree;
                }
            }
            // 保存结算信息
            Random random = new Random();
            int rand = random.nextInt(899999) + 100000;
            pay_id = KeyGenerator.generateNoFromDate("P", "yyyyMMddHHmmssS") + Integer.toString(rand);
            if (declarationFrees == null) {
                declarationFrees = new ArrayList<DeclarationFree>();
            }
            for (Declaration d : declarations) {
                try {
                    String hql = "from com.mrd.gtimp.business.entity.DeclarationFree Free where Free.declaration.id='" + d.getId() + "'";
                    List<DeclarationFree> freelist = declarationFreeBiz.findEntityByHql(hql, 0, 5, null);
                    DeclarationFree free;
                    if (freelist != null && freelist.size() > 0) {
                        free = freelist.get(0);
                        free.setPay_id(pay_id);
                        free.setDeclaration(d);
                        free.setFree(d.getDeclaration_free().toString());
                        free.setSum_free(sum.toString());
                        declarationFreeBiz.saveOrupdateEntity(free);
                        declarationFrees.add(free);
                    } else {
                        free = new DeclarationFree();
                        free.setPay_id(pay_id);
                        free.setDeclaration(d);
                        free.setFree(d.getDeclaration_free().toString());
                        free.setSum_free(sum.toString());
                        declarationFreeBiz.saveOrupdateEntity(free);
                        declarationFrees.add(free);
                    }
                    if (free.getFree() != null && !"".equals(free.getFree())) {
                        if ("0.0".equals(free.getFree()) || "0".equals(free.getFree())) {
                            // setId(free.getDeclaration().getId());
                            ids = free.getDeclaration().getId();
                            Objects.equals(payment_Type, "2");
                            updatePaymentType(ids, payment_Type);
                        }
                    }
                } catch (SaveException e) {
                    e.printStackTrace();
                }
            }
            sum_free = sum.toString();
            if (sum == 0) {
                bizConfirm(declaration_id);
            }
            HttpUtils.getRequest().setAttribute("sum_free", sum_free);
            HttpUtils.getRequest().setAttribute("pay_id", pay_id);
            HttpUtils.getRequest().setAttribute("declarations", declarations);
            HttpUtils.getRequest().setAttribute("balance", fundFlowBiz.findCurrentBalance(LoginUtil.getLoginUser().getCompany().getId()));
        }
        return "/gtimp/declaration/confirmPay";
    }

    /**
     * 增加"市场购买家私"费用
     */
    @RequestMapping("/declaration-countMMFFree")
    private Double countMMFFree(Declaration d) {
        return new Double(d.getDeclarationFreeDetail().getMmf_free()) * Integer.parseInt(d.getContainer_num());
    }

    /**
     * 增加"现在办熏蒸"
     */
    @RequestMapping("/declaration-countSteamingFree")
    private Double countSteamingFree(Declaration d) {
        return new Double(d.getDeclarationFreeDetail().getSteaming_base()) + Integer.parseInt(d.getContainer_num()) * new Double(d.getDeclarationFreeDetail().getSteaming_container());
    }

    /**
     * 增加"现场办通关单"
     */
    @RequestMapping("/declaration-countClearanceFree")
    private Double countClearanceFree(Declaration d) {
        return new Double(d.getDeclarationFreeDetail().getInner_inspection()) - new Double(d.getDeclarationFreeDetail().getOutter_inspection());
    }

    /**
     * 业务提交
     */
    @RequestMapping("/declaration-bizConfirm")
    @ResponseBody
    public Result bizConfirm(String[] declaration_ids) {
        return declarationBiz.bizConfirm(declaration_ids);
    }

    /**
     * 更新declaration的支付状态
     *
     * @param id 修改页面传回报关id
     */
    @RequestMapping("/declaration-updatePaymentType")
    public String updatePaymentType(String id, String payment_Type) {
        try {
            declarationBiz.updatePaymentType(id, payment_Type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询
     *
     * @param loadPage     用于标识是否为载入报关历史业务的页面
     * @param declaraState 报关列表状态
     */
    @RequestMapping("/declaration-findList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("container_no"), @JField("contract_no"),@JField("enter_page"), @JField("company_name"), @JField("supCompany.name"), @JField("shipper.company"), @JField("confirmTime"), @JField("state"), @JField("operateState"), @JField("declarationInform.confirmState"), @JField("creator"), @JField("validator.name"), @JField("validator.mobile"), @JField("download"), @JField("bpk"), @JField("sno"), @JField("uploadDiDan.id")})
    public Page<Declaration> findList(String loadPage, String declaraState, Jqgrid jqgrid) {
        Filter filters = jqgrid.getFilters();
        ArrayList<Declaration> declarations = null;
        String comId = LoginUtil.getLoginUser().getCompany().getId();// 此处为客户
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("customer.id", SearchRuleOption.eq, comId);
            // SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            if (StringUtils.isNotEmpty(declaraState)) {
                declaraState = declaraState.substring(0, 4);
            }
            //// TODO: 2016/8/30 filters
            if ("DS00".equals(declaraState)) {// 草稿和驳回
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.in, BaseTypeConstant.DECLARATIONSTATE_00);
                filters.addRule(rule2);
            } else if ("DS01".equals(declaraState)) {// 提交，提交待审核，已受理
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.nc, BaseTypeConstant.DECLARATIONSTATE_00 + "," + BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            } else if ("DS03".equals(declaraState) || StringUtils.isEmpty(declaraState)) {
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.in, BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            }
            // page = initPage(declarationBiz.findEntityCount(filters));
            // Order order = new Order();
            // if (null != sidx && !"".equals(sidx)) {
            // order.add(sidx, sord);
            // }

            String listCase = "select sval.chn, declaration from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval where declaration.state=sval.identifier ";
            String listCaseCount = "select count(*) from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval where declaration.state=sval.identifier ";
            String whereCase = "";
            if ("load".equals(loadPage)) {
                whereCase += " and declaration.state in('DS02','DS04','DS05') ";
            }
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Declaration.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            if (sr.getOp().equals(SearchRuleOption.lt) || sr.getOp().equals(SearchRuleOption.le)) {
                                data = "to_date('" + data + " 23:59:59','yyyy-MM-dd hh24:mi:ss')";
                            } else {
                                data = "to_date('" + data + "','yyyy-MM-dd')";
                            }
                            isDate = true;
                        }
                    }
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and declaration." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                        whereCase = whereCase + " and declaration." + field + " not in (" + data + ") ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.in)) {
                        // data = "'" + data.toString().substring(0, 4) + "'" + "," + "'"
                        // + data.toString().substring(5, 9) + "'";
                        whereCase = whereCase + " and declaration." + field + " in ('" + data + "')";
                    } else {
                        whereCase = whereCase + " and declaration." + field + " like '%" + data + "%' ";
                    }
                }
            }
            // for (String key : order.keySet()) {
            // // String[] str = key.split(",");
            // // String key_val = "";
            // // for(int i = 0;i < str.length;i++) {
            // // key_val += "declaration." + str[i] + ",";
            // // }
            // // key_val = key_val.substring(0, key_val.length() - 1);
            // // whereCase = whereCase + " order by " + key_val + " "
            // // + (order.get(key) ? "desc" : "asc") + " ";
            // whereCase = whereCase + " order by declaration." + key + " "
            // + (order.get(key) ? "desc" : "asc") + " ";
            // }
            listCaseCount = listCaseCount + whereCase;
            int count = declarationBiz.findEntityCountByHql(listCaseCount, null);
            List<Object> objList = declarationBiz.findObjectByHql(listCase, jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
            if (null != objList && objList.size() > 0) {
                if (declarations == null) {
                    declarations = new ArrayList<Declaration>();
                }
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Declaration b = (Declaration) os[1];
                    b.setDecState(os[0].toString());
                    declarations.add(b);
                }
            }
            Page<Declaration> page = new PageImpl<>(declarations, jqgrid.getPage(), count);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户报表查询
     *
     * @param declaraState 报关列表状态
     */
    @RequestMapping("/declaration-customerDeclarationReporFindtList")
    @ResponseBody
    @Json({@JField("id"), @JField("confirmTime"), @JField("businessId"), @JField("company_name"),@JField("enter_page"), @JField("container_no"), @JField("sno"), @JField("contract_no"), @JField("supCompany.name"), @JField("declaration_port"), @JField("creator"), @JField("state"), @JField("declaration_free"), @JField("pay_id"), @JField("bpk")})
    public Page<Declaration> customerDeclarationReporFindtList(String declaraState, Jqgrid jqgrid) {
        List<Declaration> declarations = null;
        Filter filters = jqgrid.getFilters();
        String comId = LoginUtil.getLoginUser().getCompany().getId();// 此处为客户
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            //// TODO: 2016/8/31 filters
            SearchRule rule = new SearchRule("customer.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            if ("DS00".equals(declaraState)) {// 草稿和驳回
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.in, BaseTypeConstant.DECLARATIONSTATE_00);
                filters.addRule(rule2);
            } else if ("DS01".equals(declaraState)) {// 提交，提交待审核，已受理
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.nc, BaseTypeConstant.DECLARATIONSTATE_00 + "," + BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            } else if ("DS03".equals(declaraState)) {
                SearchRule rule2 = new SearchRule("state", SearchRuleOption.in, BaseTypeConstant.DECLARATIONSTATE_03);
                filters.addRule(rule2);
            }
            // Order order = new Order();
            // if (null != sidx && !"".equals(sidx)) {
            // order.add(sidx, sord);
            // }

            String listCase = "select sval.chn, declaration, df.free, df.pay_id " + "from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval, " + "com.mrd.gtimp.business.entity.DeclarationFree df " + "where declaration.state=sval.identifier and df.declaration.id=declaration.id and df.pay_comfirm='1' ";
            String listCaseCount = "select count(*) " + "from com.mrd.gtimp.business.entity.Declaration declaration, com.mrd.gtimp.base.entity.SystemValue sval, " + "com.mrd.gtimp.business.entity.DeclarationFree df " + "where declaration.state=sval.identifier and df.declaration.id=declaration.id and df.pay_comfirm='1' ";
            String whereCase = "";
            whereCase += " and declaration.state not in ('DS00','DS03','DS05') ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Declaration.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            if (sr.getOp().equals(SearchRuleOption.lt) || sr.getOp().equals(SearchRuleOption.le)) {
                                data = "to_date('" + data + " 23:59:59','yyyy-MM-dd hh24:mi:ss')";
                            } else {
                                data = "to_date('" + data + "','yyyy-MM-dd')";
                            }
                            isDate = true;
                        }
                    }
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and declaration." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                        whereCase = whereCase + " and declaration." + field + " not in (" + data + ") ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and declaration." + field + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.in)) {
                        whereCase = whereCase + " and declaration." + field + " in ('" + data + "')";
                    } else {
                        whereCase = whereCase + " and declaration." + field + " like '%" + data + "%' ";
                    }
                }
            }
            // for (String key : order.keySet()) {
            // whereCase = whereCase + " order by declaration." + key + " "
            // + (order.get(key) ? "desc" : "asc") + " ";
            // }
            listCase = listCase + whereCase;
            listCaseCount = listCaseCount + whereCase;
            int count = declarationBiz.findEntityCountByHql(listCaseCount, null);
            List<Object> objList = declarationBiz.findObjectByHql(listCase, jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
            if (null != objList && objList.size() > 0) {
                if (declarations == null) {
                    declarations = new ArrayList<Declaration>();
                }
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Declaration b = (Declaration) os[1];
                    b.setDecState(os[0].toString());
                    b.setDeclaration_free(Double.parseDouble(os[2].toString()));
                    b.setPay_id(os[3].toString());
                    declarations.add(b);
                }
            }
            Page<Declaration> page = new PageImpl<>(declarations, jqgrid.getPage(), count);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 供应商详细报表
     */
    @RequestMapping("/declaration-supDeclarationReporFindtList")
    @ResponseBody
    @Json({@JField("id"), @JField("confirmTime"), @JField("businessId"), @JField("shipper.company"),@JField("enter_page"), @JField("company_name"), @JField("container_no"), @JField("supCompany.name"), @JField("declaration_port"), @JField("state"), @JField("declaration_free"), @JField("pay_id"), @JField("bpk")})
    public Page<Declaration> supDeclarationReporFindtList(Jqgrid jqgrid) {
        List<Declaration> declarations = new ArrayList<>();
        Filter filters = jqgrid.getFilters();
        String comId = LoginUtil.getLoginUser().getCompany().getId();// 此处为供应商
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            // SearchRule rule2 = new SearchRule("state", SearchRuleOption.ni,
            // BaseTypeConstant.DECLARATIONSTATE_00 + "," + BaseTypeConstant.DECLARATIONSTATE_03);
            // filters.addRule(rule2);

            // Order order = new Order();
            // if (null != sidx && !"".equals(sidx)) {
            // order.add(sidx, sord);
            // }

            String listCase = "select sval.chn, declaration, df.free, df.pay_id from com.mrd.gtimp.business.entity.Declaration declaration, " + "com.mrd.gtimp.base.entity.SystemValue sval, com.mrd.gtimp.business.entity.DeclarationFree df " + " where declaration.state=sval.identifier and df.declaration.id=declaration.id and (1=1 and df.pay_comfirm='1' ";
            String listCaseCount = "select count(*) from com.mrd.gtimp.business.entity.Declaration declaration, " + "com.mrd.gtimp.base.entity.SystemValue sval, com.mrd.gtimp.business.entity.DeclarationFree df " + "where declaration.state=sval.identifier and df.declaration.id=declaration.id and (1=1 and df.pay_comfirm='1' ";
            String whereCase = "";

            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and declaration." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and declaration." + field + " not in ('" + data + "') ";
                    } else if (sr.getOp() == SearchRuleOption.ni) {
                        whereCase = whereCase + " and declaration." + field + " not in ('" + data + "') ";
                    }
                }
            }
            // 业务流转查询
            whereCase = whereCase + " or declaration.id in (select bf.bizId from com.mrd.gtimp.business.entity.BizFlow bf where bf.scompany='" + comId + "' or bf.tcompany='" + comId + "')) ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Declaration.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            if (sr.getOp().equals(SearchRuleOption.lt) || sr.getOp().equals(SearchRuleOption.le)) {
                                data = "to_date('" + data + " 23:59:59','yyyy-MM-dd hh24:mi:ss')";
                            } else {
                                data = "to_date('" + data + "','yyyy-MM-dd')";
                            }
                            isDate = true;
                        }
                    }
                    if (!"supCompany.id".equals(field) && !data.equals(BaseTypeConstant.DECLARATIONSTATE_00)) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and declaration." + field + " ='" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'" + "," + "'" + data.toString().substring(10, 14) + "'";
                            whereCase = whereCase + " and declaration." + field + " not in (" + data + ")";
                        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " > " + data : " > '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " < " + data : " < '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " >= " + data : " >= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.le)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " <= " + data : " <= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.in)) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                            whereCase = whereCase + " and declaration." + field + " in(" + data + ")";
                        } else if (sr.getOp().equals(SearchRuleOption.ni)) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                            whereCase = whereCase + " and declaration." + field + " not in (" + data + ")";
                        } else {
                            whereCase = whereCase + " and declaration." + field + " like '%" + data + "%' ";
                        }
                    }
                }
            }
            // for (String key : order.keySet()) {
            // whereCase = whereCase + " order by declaration." + key + " "
            // + (order.get(key) ? "desc" : "asc") + " ";
            // }
            listCase = listCase + whereCase;
            listCaseCount = listCaseCount + whereCase;
            int count = declarationBiz.findEntityCountByHql(listCaseCount, null);
            List<Object> objList = declarationBiz.findObjectByHql(listCase, jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
            if (null != objList && objList.size() > 0) {
                if (declarations == null) {
                    declarations = new ArrayList<Declaration>();
                }
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Declaration b = (Declaration) os[1];
                    b.setDecState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0].toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0].toString());
                    b.setDecState(os[0].toString());
                    b.setDeclaration_free(Double.parseDouble(os[2].toString()));
                    b.setPay_id(os[3].toString());
                    String realSupId = b.getRealSupId();
                    if (StringUtils.isNotEmpty(realSupId)) {
                        if (realSupId.equals(comId)) {
                            b.setRealSupId(realSupId + ":业务流入");
                        } else {
                            b.setRealSupId(realSupId + ":业务流出");
                        }
                    }
                    declarations.add(b);
                }
            }
            Page<Declaration> page = new PageImpl<>(declarations, jqgrid.getPage(), count);
            if (page != null && page.getSize() > 0) {
                return page;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 平台对账表明细
     */
    @RequestMapping("/declaration-platFormDeclarationReporFindtList")
    @ResponseBody
    @Json({@JField("id"), @JField("confirmTime"), @JField("businessId"), @JField("shipper.company"), @JField("company_name"),@JField("enter_page"), @JField("container_no"), @JField("sno"), @JField("supCompany.name"), @JField("declaration_port"), @JField("state"), @JField("declaration_free"), @JField("pay_id"), @JField("bpk")})
    public Page<Declaration> platFormDeclarationReporFindtList(Jqgrid jqgrid) {
        List<Declaration> declarations = new ArrayList<Declaration>();
        Filter filters = jqgrid.getFilters();
        try {
            //// TODO: 2016/9/1 filters
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            String listCase = "select sval.chn, declaration, df.free, df.pay_id from com.mrd.gtimp.business.entity.Declaration declaration, " + "com.mrd.gtimp.base.entity.SystemValue sval, com.mrd.gtimp.business.entity.DeclarationFree df " + " where declaration.state=sval.identifier and df.declaration.id=declaration.id and (1=1 and df.pay_comfirm='1' ";
            String listCaseCount = "select count(*) from com.mrd.gtimp.business.entity.Declaration declaration, " + "com.mrd.gtimp.base.entity.SystemValue sval, com.mrd.gtimp.business.entity.DeclarationFree df " + "where declaration.state=sval.identifier and df.declaration.id=declaration.id and (1=1 and df.pay_comfirm='1' ";
            String whereCase = "";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and declaration." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and declaration." + field + " not in ('" + data + "') ";
                    } else if (sr.getOp() == SearchRuleOption.ni) {
                        whereCase = whereCase + " and declaration." + field + " not in ('" + data + "') ";
                    }
                }
            }
            // 业务流转查询
            whereCase = whereCase + " ) ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Declaration.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            if (sr.getOp().equals(SearchRuleOption.lt) || sr.getOp().equals(SearchRuleOption.le)) {
                                data = "to_date('" + data + " 23:59:59','yyyy-MM-dd hh24:mi:ss')";
                            } else {
                                data = "to_date('" + data + "','yyyy-MM-dd')";
                            }
                            isDate = true;
                        }
                    }
                    if (!"supCompany.id".equals(field) && !data.equals(BaseTypeConstant.DECLARATIONSTATE_00)) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and declaration." + field + " ='" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'" + "," + "'" + data.toString().substring(10, 14) + "'";
                            whereCase = whereCase + " and declaration." + field + " not in (" + data + ")";
                        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " > " + data : " > '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " < " + data : " < '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " >= " + data : " >= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.le)) {
                            whereCase = whereCase + " and declaration." + field + (isDate ? " <= " + data : " <= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.in)) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                            whereCase = whereCase + " and declaration." + field + " in(" + data + ")";
                        } else if (sr.getOp().equals(SearchRuleOption.ni)) {
                            data = "'" + data.toString().substring(0, 4) + "'" + "," + "'" + data.toString().substring(5, 9) + "'";
                            whereCase = whereCase + " and declaration." + field + " not in (" + data + ")";
                        } else {
                            whereCase = whereCase + " and declaration." + field + " like '%" + data + "%' ";
                        }
                    }
                }
            }
            listCase = listCase + whereCase;
            listCaseCount = listCaseCount + whereCase;
            int count = declarationBiz.findEntityCountByHql(listCaseCount, null);
            List<Object> objList = declarationBiz.findObjectByHql(listCase, jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
            if (null != objList && objList.size() > 0) {
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Declaration b = (Declaration) os[1];
                    b.setDecState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0].toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0].toString());
                    b.setDecState(os[0].toString());
                    b.setDeclaration_free(Double.parseDouble(os[2].toString()));
                    b.setPay_id(os[3].toString());
                    declarations.add(b);
                }
            }
            Page<Declaration> page = new PageImpl<>(declarations, jqgrid.getPage(), count);
            if (page != null && page.getSize() > 0) {
                return page;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/declaration-findBizState")
    @ResponseBody
    public Result findBizState() {
        Result msg = null;
        //// TODO: 2016/8/15 service
        try {
            // String id = HttpUtils.getParam("id");
            // Declaration entity = declarationBiz.findEntityById(id);
            // SupBizServiceClient client = new SupBizServiceClient();
            // SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
            // // String serviceUrl =
            // "http://localhost:8086/cams/ws/supDeclarationBizService?wsdl";//
            // // 本地
            // // String serviceUrl =
            // // "http://112.124.20.178:18080/cams/ws/supDeclarationBizService?wsdl";// 新港
            // String serviceUrl = SystemConstants.SERVICE_URL_8080;
            // System.out.println("findBizState======" + serviceUrl);
            // qdto.setServiceUrl(serviceUrl);
            // // String bizPk = entity.getBpk();
            // // qdto.setBizPk(bizPk);
            // String work_no = entity.getWork_no();// 获取三联单编号
            // qdto.setBizPk(work_no);
            // String result = client.findDeclarationBizState(qdto);
            // msg = result;
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/declaration-findBizResult")
    public String findBizResult() {
        try {
            String id = HttpUtils.getParam("id");
            // get url
            // get bpk
            Declaration entity = declarationBiz.findEntityById(id);

            //// TODO: 2016/8/15 service
            // SupBizServiceClient client = new SupBizServiceClient();
            // SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
            // // String serviceUrl = "http://localhost:8086/cams/ws/supDeclarationBizService?wsdl";
            // // String serviceUrl =
            // // "http://112.124.20.178:18080/cams/ws/supDeclarationBizService?wsdl";// 新港
            // String serviceUrl = SystemConstants.SERVICE_URL_8080;
            // System.out.println("findBizResult======" + serviceUrl);
            // qdto.setServiceUrl(serviceUrl);
            // // String bizPk = entity.getBpk();
            // String bizPk = entity.getWork_no();
            // qdto.setBizPk(bizPk);
            // SupDeclarationBizResultDTO result = client.findDeclarationBizResult(qdto);
            // request.setAttribute("resultDTO", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/gtimp/declaration/declarationResult";
    }

    @RequestMapping("/declaration-findBizPassInfo")
    public String findBizPassInfo(Declaration declaration) {
        try {
            String id = HttpUtils.getParam("id");
            declaration = declarationBiz.findEntityById(id);
            HttpUtils.getRequest().setAttribute("resultDTO", declaration);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/gtimp/declaration/declarationPassInfo";
    }

    @RequestMapping("/declaration-addInform")
    @ResponseBody
    public Result addInform() {
        Result msg;
        String id = HttpUtils.getParam("id");
        try {
            declarationBiz.updateBizAddInform(id);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;

    }

    @RequestMapping("/declaration-dowmlaodDeclara")
    @ResponseBody
    public Result dowmlaodDeclara(Declaration declaration) throws Exception {
        Result msg = null;
        String id = HttpUtils.getParam("id");
        String uploadDiDanId = HttpUtils.getParam("uploadDiDanId");
        try {
            declaration = declarationBiz.findEntityById(id);
            // String bpk = declaration.getBpk();
            // JSONObject jsonobj = JSONObject.fromObject(bpk);
            // String sno = jsonobj.get("sno").toString();
            String sno = declaration.getSno();
            //// TODO: 2016/8/15 service
            SupBizServiceClient client = new SupBizServiceClient();
            SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
            // // String serviceUrl = "http://localhost:8086/cams/ws/supDeclarationBizService?wsdl";
            // // String serviceUrl =
            // "http://192.168.0.5:9280/cams/ws/supDeclarationBizService?wsdl";
            String serviceUrl = SystemConstants.SERVICE_URL_8080;
            System.out.println("dowmlaodDeclara=serviceUrl=========" + serviceUrl);
            qdto.setServiceUrl(serviceUrl);
            // 处理因为佛港报关号是九位，单一窗口反填18位导致不能下载底单的问题
            int normalLen = 9;
            int snoLength = sno.length();
            if (StringUtils.isNotEmpty(sno)) {
                if (snoLength > normalLen) {
                    sno = sno.substring(snoLength - normalLen, snoLength);
                }
            }
            qdto.setBizPk(sno);
            String downloadPath = client.declarationDownloadPath(qdto);
            System.out.println("dowmlaodDeclara_downloadPath=========" + downloadPath);
            if (!"".equals(downloadPath)) {
                msg = Result.newSuccessInstance(MsgConstants.DOWN_DECLARATION_SUCCESS_NEW, downloadPath);
                // // downloadDeclarationFile(downloadPath, response);
                // // msg = "{\"state\":0,\"msg\":\"" + downloadPath + "\"}";
            } else {
                // if (StringUtils.isNotEmpty(uploadDiDanId)) {
                // // 下载本地上传的底单
                // Attachment at = attachmentBiz.findEntityById(uploadDiDanId);
                // downloadFileName = at.getName();
                // // 解决下载文件名的中文乱码
                // downloadFileName = new String(downloadFileName.getBytes("gb2312"), "ISO-8859-1");
                // // path = at.getReplacename();
                // path = at.getPath();
                // HttpServletRequest request = ServletActionContext.getRequest();
                // @SuppressWarnings("deprecation")
                // String realPath = request.getRealPath("/");
                // File file = new File(realPath.substring(0, realPath.length() - 1) + path);
                // if (file.exists() && file.isFile()) {
                // msg = MsgConstants.DOWN_DECLARATION_SUCCESS;
                // } else {
                // msg = MsgConstants.DOWN_DECLARATION_ERROR;
                // }
                // } else {
                // msg = MsgConstants.DOWN_DECLARATION_ERROR;
                // }
                msg = Result.newFailInstance(MsgConstants.DOWN_DECLARATION_ERROR_NEW);
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/declaration-downloadDeclarationFile")
    public void downloadDeclarationFile(HttpServletResponse response, Declaration declaration) {
        OutputStream out = null;
        InputStream in = null;
        String zipPath = null;
        int len;
        byte[] buff = new byte[2048];
        String id = HttpUtils.getParam("id");
        try {
            declaration = declarationBiz.findEntityById(id);
            // String bpk = declaration.getBpk();
            // JSONObject jsonobj = JSONObject.fromObject(bpk);
            // String sno = jsonobj.get("sno").toString();
            String sno = declaration.getSno();
            // 处理因为佛港报关号是九位，单一窗口反填18位导致不能下载底单的问题
            int normalLen = 9;
            int snoLength = sno.length();
            if (StringUtils.isNotEmpty(sno)) {
                if (snoLength > normalLen) {
                    sno = sno.substring(snoLength - normalLen, snoLength);
                }
            }
            //// TODO: 2016/8/15 service
            SupBizServiceClient client = new SupBizServiceClient();
            SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
            // // String serviceUrl = "http://localhost:8086/cams/ws/supDeclarationBizService?wsdl";
            // // String serviceUrl =
            // "http://192.168.0.5:9280/cams/ws/supDeclarationBizService?wsdl";
            String serviceUrl = SystemConstants.SERVICE_URL_8080;
            System.out.println("downloadDeclarationFile=serviceUrl=========" + serviceUrl);
            qdto.setServiceUrl(serviceUrl);
            qdto.setBizPk(sno);
            String downloadPath = client.declarationDownloadPath(qdto);
            System.out.println("downloadPath==========" + downloadPath);
            zipPath = ZipUtil.add(downloadPath);
            System.out.println("zipPath==========" + zipPath);
            // 下载
            // response.setContentType("text/html;charset=utf-8");
            // response.setContentType("application/octet-stream");
            // response.setHeader("content-disposition", "attachment;filename="
            // + new File(zipPath).getName());
            response.setContentType("text/html;charset=utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + new File(zipPath).getName());

            in = new BufferedInputStream(new FileInputStream(new File(zipPath)));
            out = new BufferedOutputStream(response.getOutputStream());
            while (-1 != (len = in.read(buff))) {
                out.write(buff, 0, len);
            }
            // String queryDownloadTimes =
            // "SELECT B.DOWNLOAD_TIMES FROM BG_CUSTOMS_DECLARATION B WHERE B.SNO IN ("
            // + Snos.substring(0, Snos.length() - 1) + ")";
            // List<?> times = dao.findListBySql(queryDownloadTimes);
            // // 记录下载次数
            // String recordDownloadTimesSql = "";
            // if(times.get(0) == null) {
            // recordDownloadTimesSql =
            // "UPDATE BG_CUSTOMS_DECLARATION B SET B.DOWNLOAD_TIMES = 1 WHERE B.SNO = '"
            // + ss[0] + "'";
            // } else {
            // int object = Integer.parseInt(times.get(0).toString());
            // recordDownloadTimesSql = "UPDATE BG_CUSTOMS_DECLARATION B SET B.DOWNLOAD_TIMES = "
            // + ++object + " WHERE B.SNO = " + ss[0];
            // }
            // dao.updateBySQL(recordDownloadTimesSql);
            // System.out.println("下载时间："
            // + new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date()) + "报关单号："
            // + ss[0]);
        } catch (Exception e) {
            String s = e.getClass().getSimpleName();
            if (!"ClientAbortException".equals(s)) {
                e.printStackTrace();
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ZipUtil.removeFile(zipPath);
        }
    }

    /**
     * 从新港获取柜号
     */
    @RequestMapping("/declaration-getContainerInfoVal")
    @ResponseBody
    public Map<String, String> getContainerInfoVal(String container_no, String work_type, String declaration_type) throws Exception {
        SupBizServiceClient client = new SupBizServiceClient();
        SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
        String serviceUrl = SystemConstants.SERVICE_URL_8080;
        qdto.setServiceUrl(serviceUrl);
        qdto.setBizPk(container_no);
        qdto.setWork_type(work_type);
        qdto.setDeclaration_type(declaration_type);
        String containerInfo = client.declarationGetContainerInfo(qdto);
        Map<String, String> json = new HashMap<>();
        json.put("containerInfo", containerInfo);
        return json;
    }

    /**
     * 绑定报关单输入界面
     */
    @RequestMapping("/declaration-bindingDeclarationNum")
    public String bindingDeclarationNum() {
        HttpUtils.getRequest().setAttribute("id", HttpUtils.getParam("id"));
        return "/gtimp/declaration/bindingDeclarationNumber";
    }

    /**
     * 上载底单界面
     */
    @RequestMapping("/declaration-uploadDiDan")
    public String uploadDiDan(Declaration declaration) {
        String id = HttpUtils.getParam("id");
        try {
            declaration = declarationBiz.findEntityById(id);
            HttpUtils.getRequest().setAttribute("declaration", declaration);
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return "/gtimp/declaration/uploadDiDan";
    }

    @RequestMapping("/declaration-doBindingDeclarationNumber")
    public String doBindingDeclarationNumber(Declaration declaration) {
        try {
            String id = HttpUtils.getParam("id");
            List<String> properties = new ArrayList<String>();
            properties.add("sno");
            declaration.setId(id);
            declarationBiz.updateEntity(declaration, properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 报关单绑定上传底单
     */
    @RequestMapping("/declaration-doBindingUpLoadId")
    @ResponseBody
    public Result doBindingUpLoadId() {
        Result msg;
        String upLoadId = HttpUtils.getParam("upLoadId");
        String declarationId = HttpUtils.getParam("declarationId");
        System.out.println(upLoadId + "=====" + declarationId);
        String sql = "update t_biz_declaration set didan_file_id='" + upLoadId + "' where id='" + declarationId + "'";
        try {
            declarationBiz.updateBySql(sql);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/declaration-doGetContainerInCTMS")
    @ResponseBody
    public String doGetContainerInCTMS() throws Exception {
        String key = HttpUtils.getParam("key");
        SupBizServiceClient client = new SupBizServiceClient();
        SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
        String serviceUrl = SystemConstants.SERVICE_URL_8080;
        qdto.setServiceUrl(serviceUrl);
        qdto.setBizPk(key);
        String containerInfo = client.declarationGetPastContainerInfo(qdto);
        return containerInfo;
    }

    public List<String> getMmf_ids_ids() {
        return mmf_ids_ids;
    }

    public void setMmf_ids_ids(List<String> mmf_ids_ids) {
        this.mmf_ids_ids = mmf_ids_ids;
    }

    public List<String> getDeclaration_ids() {
        return declaration_ids;
    }

    public void setDeclaration_ids(List<String> declaration_ids) {
        this.declaration_ids = declaration_ids;
    }

    public String getPayment_Type() {
        return payment_Type;
    }

    public void setPayment_Type(String payment_Type) {
        this.payment_Type = payment_Type;
    }

    // ======================================GTIMP 3.0======================

    @Resource
    private InspectionGoodsBiz inspectionGoodsBiz;

    /**
     * 供应商-待受理主页
     */
    @RequestMapping("/toValidMain")
    public String toValidMain() {
        return "gtimp3/declaration/toValidMain";
    }

    /**
     * 供应商-待受理操作页面
     */
    @RequestMapping("/toValid")
    public String toValid() {
        return "gtimp3/declaration/toValid";
    }

    /**
     * 前端传入id时，核对是否属于当前供应商的订单
     */
    private Declaration findSupperDeclaration(String id, String supComId) throws QueryException {
        if (null == supComId) {
            supComId = LoginUtil.getLoginUser().getCompany().getId();
        }
        return declarationBiz.findEntityById(id);
    }

    /**
     * 供应商-受理操作
     */
    @RequestMapping("/doValid")
    @ResponseBody
    public Result doValid(String id) {
        if (StringUtils.isNoneEmpty(id)) {
            try {
                Declaration entity = findSupperDeclaration(id, null);
                if (entity != null && StringUtils.isNoneEmpty(entity.getId())) {
                    if ("DS01".equals(entity.getState())) {
                        declarationBiz.doValidAndLogOpa(entity);
                        hongbaoBiz.sendHongBao(entity);
                        Company company = entity.getSupCompany();
                        if (StringUtils.isNotEmpty(company.getIsSignWS()) && company.getIsSignWS().equals("1")) {
                            try {
                                entity.setConfirmType("0");
                                declarationBiz.confirmSanLianDan(entity);
                            } catch (Exception e) {
                                e.printStackTrace();
                                return Result.newSuccessInstance("提交成功。保存三联单失败，请手工确认三联单。");
                            }
                            return Result.newSuccessInstance("提交成功。保存三联单成功。");
                        }
                        return Result.newSuccessInstance("受理成功。");
                    } else {
                        String msg = "单证不能受理，请确认单证状态为已提交待审核状态或刷新后重试。\n";
                        logger.error(String.format("%s,%s", entity.getId(), msg));
                        return Result.newFailInstance(msg);
                    }
                } else {
                    String msg = "报关单不存在。";
                    logger.error(String.format("%s,%s，%s", id, LoginUtil.getLoginUser().getCompany().getId(), msg));
                    return Result.newFailInstance(msg);
                }
            } catch (QueryException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            } catch (SaveException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            }
        }
        return Result.newFailInstance("操作失败.");
    }

    /**
     * 供应商-受理操作
     */
    @RequestMapping("/doSecondSupValid")
    @ResponseBody
    public Result doSecondSupValid(String id, String secondSupId, String secondSupIdCode) {
        if (StringUtils.isNoneEmpty(id)) {
            try {
                Declaration entity = findSupperDeclaration(id, null);
                entity.setSecondSupId(secondSupId);
                entity.setSecondSupIdCode(secondSupIdCode);
                if (entity != null && StringUtils.isNoneEmpty(entity.getId())) {
                    if ("DS01".equals(entity.getState())) {
                        declarationBiz.doSecondSupValidAndLogOpa(entity);
                        hongbaoBiz.sendHongBao(entity);
                        return Result.newSuccessInstance("提交成功.");
                    } else {
                        String msg = "单证不能受理，请确认单证状态为已提交待审核状态或刷新后重试。\n";
                        logger.error(String.format("%s,%s", entity.getId(), msg));
                        return Result.newFailInstance(msg);
                    }
                } else {
                    String msg = "报关单不存在。";
                    logger.error(String.format("%s,%s，%s", id, LoginUtil.getLoginUser().getCompany().getId(), msg));
                    return Result.newFailInstance(msg);
                }
            } catch (QueryException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            } catch (SaveException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            } catch (Exception e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            }
        }
        return Result.newFailInstance("操作失败.");
    }

    /**
     * 供应商-驳回操作页面
     */
    @RequestMapping("/toReject")
    public String toReject(Model model, String id) {
        if (StringUtils.isNotEmpty(id)) {
            model.addAttribute("id", id);
        }
        return "gtimp3/declaration/toReject";
    }

    /**
     * 供应商-驳回操作
     */
    @RequestMapping("/doReject")
    @ResponseBody
    public Result doReject(String id, String content) {
        if (StringUtils.isNoneEmpty(id)) {
            try {
                Declaration entity = findSupperDeclaration(id, null);
                if (entity != null && StringUtils.isNoneEmpty(entity.getId())) {
                    if ("DS01".equals(entity.getState()) || "DS02".equals(entity.getState()) || "DS04".equals(entity.getState())) {
                        declarationBiz.doRejectAndLogOpa(entity, content);
                        return Result.newSuccessInstance("提交成功.");
                    } else {
                        String msg = "单证不能驳回，请确认单证状态为已提交待审核或刷新后重试。\n";
                        logger.error(String.format("%s,%s", entity.getId(), msg));
                        return Result.newFailInstance(msg);
                    }
                } else {
                    String msg = "报关单不存在。";
                    logger.error(String.format("%s,%s，%s", id, LoginUtil.getLoginUser().getCompany().getId(), msg));
                    return Result.newFailInstance(msg);
                }
            } catch (QueryException e) {
                e.printStackTrace();
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            } catch (SaveException e) {
                e.printStackTrace();
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            } catch (Exception e) {
                e.printStackTrace();
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            }
        }
        return Result.newFailInstance("操作失败.");
    }

    /**
     * 确认三联单
     */
    @RequestMapping("/confirmSanLianDan")
    @ResponseBody
    public Result confirmSanLianDan(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            StringBuffer failedResult = new StringBuffer();
            for (String id : ids.split(",")) {
                if (StringUtils.isNotEmpty(id)) {
                    Declaration declaration = null;
                    try {
                        declaration = declarationBiz.findEntityById(id);
                        if (StringUtils.isNotEmpty(declaration.getConfirmType()) && declaration.getConfirmType().equals("1")) {
                            failedResult.append(declaration.getBusinessId() + ":已确认三联单，不能重复确认;");
                            continue;
                        }
                        if ("转关".equals(declaration.getData_type()) && StringUtils.isEmpty(declaration.getTransport_na())) {
                            failedResult.append(declaration.getBusinessId()).append("：必须填写转关纸号\n");
                            continue;
                        }
                        declaration.setConfirmType("1");
                        declarationBiz.confirmSanLianDan(declaration);
                    } catch (QueryException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        if (declaration != null) {
                            failedResult.append(declaration.getBusinessId() + ":确认三联单失败;");
                        }
                        e.printStackTrace();
                    }
                }
            }
            if (failedResult.length() > 1) {
                return Result.newFailInstance(failedResult.toString());
            }
            return Result.newSuccessInstance("操作成功");
        }
        return Result.newFailInstance("请选择需要确认的报关单");
    }

    /**
     * 供应商-已受理主页
     */
    @RequestMapping("/validMain")
    public String validMain(Model model) {
        Company company = LoginUtil.getLoginUser().getCompany();
        if (company.getName().contains("佛港报关")) {
            model.addAttribute("isFG", true);
        } else {
            model.addAttribute("isFG", false);
        }
        if (StringUtils.isNotEmpty(company.getIsSignWS()) && company.getIsSignWS().equals("1")) {
            model.addAttribute("isSignWS", true);
        } else {
            model.addAttribute("isSignWS", false);
        }
        model.addAttribute("declarationWayCodes", singleWindow.currentCompanyUploadWays());
        return "gtimp3/declaration/validMain";
    }

    /**
     * 供应商-绑定报关单号操作
     */
    @RequestMapping("/doEditSNO")
    @ResponseBody
    public Result doEditSNO(String id, String sno) {
        if (StringUtils.isNoneEmpty(id)) {
            try {
                Declaration entity = findSupperDeclaration(id, null);
                if (entity != null && StringUtils.isNoneEmpty(entity.getId())) {
                    entity.setSno(sno);
                    try {
                        declarationBiz.saveOrupdateEntity(entity);
                        //更新新港系统报关单号
                        try {
                            new CtmsServiceClient().updateSno(id, sno);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (SaveException e) {
                        String msg = "操作失败.";
                        logger.error(String.format("%s", msg), e);
                        return Result.newFailInstance(msg);
                    }
                } else {
                    String msg = "报关单不存在。";
                    logger.error(String.format("%s,%s，%s", id, LoginUtil.getLoginUser().getCompany().getId(), msg));
                    return Result.newFailInstance(msg);
                }
            } catch (QueryException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            }
        }
        return Result.newSuccessInstance("提交成功.");
    }

    /**
     * 供应商-报关单标识放行
     */
    @RequestMapping("/doDeclarationOk")
    @ResponseBody
    public Result doDeclarationOk(String id, String okType) {
        if (StringUtils.isNoneEmpty(id)) {
            if (jedisClientCluster.get("lock_decla_" + id, String.class) != null) {
                return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
            }
            try {
                Declaration entity = findSupperDeclaration(id, null);
                if (entity != null && StringUtils.isNoneEmpty(entity.getId())) {
                    String state = entity.getState();
                    if (state.equalsIgnoreCase("DS05")) {
                        return Result.newFailInstance("该报关单数据已放行。");
                    } else if (state.equalsIgnoreCase("DS10") && okType.equalsIgnoreCase("海关放行")) {
                        return Result.newFailInstance("该报关单数据海关已放行。");
                    } else if (state.equalsIgnoreCase("DS11") && okType.equalsIgnoreCase("商检放行")) {
                        return Result.newFailInstance("该报关单数据商检已放行。");
                    }
                    if (state.equalsIgnoreCase("DS10") && okType.equalsIgnoreCase("商检放行")) {
                        entity.setState("DS05");
                    } else if (state.equalsIgnoreCase("DS11") && okType.equalsIgnoreCase("海关放行")) {
                        entity.setState("DS05");
                    } else {
                        switch (okType) {
                            case "海关放行":
                                entity.setState("DS10");
                                break;
                            case "商检放行":
                                entity.setState("DS11");
                                break;
                            case "一键放行":
                                entity.setState("DS05");
                                break;
                            default:
                        }
                    }
                    try {
                        declarationBiz.changeState(entity);
                        if (entity.getState().equalsIgnoreCase("DS05")) {
                            this.changeInspectionGoodsState(entity, "2");
                        }
                    } catch (Exception e) {
                        String msg = "操作失败.";
                        logger.error(String.format("%s", msg), e);
                        e.printStackTrace();
                        return Result.newFailInstance(msg);
                    }
                } else {
                    String msg = "报关单不存在。";
                    logger.error(String.format("%s,%s，%s", id, LoginUtil.getLoginUser().getCompany().getId(), msg));
                    return Result.newFailInstance(msg);
                }
            } catch (QueryException e) {
                String msg = "操作失败.";
                logger.error(String.format("%s", msg), e);
                return Result.newFailInstance(msg);
            }
        }
        return Result.newSuccessInstance("提交成功.");
    }

    /**
     * 根据报关单查找查验货物信息更新状态
     */
    public void changeInspectionGoodsState(Declaration declaration, String inspectionGoodsState) {
        if (declaration != null && StringUtils.isNotEmpty(declaration.getId())) {
            List<InspectionGoods> inspectionGoodsList = inspectionGoodsBiz.findByDeclaration(declaration);
            for (InspectionGoods inspectionGoods : inspectionGoodsList) {
                inspectionGoods.setState(inspectionGoodsState);
                try {
                    List<String> properties = new ArrayList<>();
                    properties.add("state");
                    inspectionGoodsBiz.updateEntity(inspectionGoods, properties);
                } catch (SaveException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 供应商-已驳回主页
     */
    @RequestMapping("/invalidMain")
    public String invalidMain() {
        return "gtimp3/declaration/invalidMain";
    }

    /**
     * 查询供应商待受理单证
     */
    @RequestMapping("/findToValidList")
    @ResponseBody
    public void findToValidList(com.mrd.base.Jqgrid jqgrid, HttpServletResponse response) {
        declarationService.findToValidList(jqgrid, response);
    }


    /**
     * 查询供应商已受理单证
     */
    @RequestMapping("/findValidList")
    @ResponseBody
    public void findValidList(com.mrd.base.Jqgrid jqgrid, HttpServletResponse response) {
        declarationService.findValidList(jqgrid, response);
    }

    /**
     * 查询供应商已驳回单证
     */
    @RequestMapping("/findInvalidList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("contract_no"), @JField("declaration_type"),@JField("enter_page"), @JField("contract_no"), @JField("company_name"), @JField("customer.name"), @JField("confirmTime"), @JField("creator"), @JField("validator.name"), @JField("validateTime"), @JField("sno"), @JField("container_no"), @JField("bl_no"), @JField("rejectContent.rejectPerson"), @JField("rejectContent.content")})
    public Page<Declaration> findInvalidList(Jqgrid jqgrid) {
        if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
            String companyId = LoginUtil.getLoginUser().getCompany().getId();
            jqgrid.addRule(new SearchRule("supCompany.id", SearchRuleOption.eq, companyId));
        }
        jqgrid.addRule(new SearchRule("state", SearchRuleOption.eq, "DS03"));
        try {
            return declarationBiz.findByJqgrid(jqgrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(DeclarationAction.class);

    @Resource
    private EvaluationBiz evaluationBiz;

    /**
     * 未付款主页
     */
    @RequestMapping("/unpaidMain")
    public String unpaidMain() {
        return "gtimp3/declaration/unpaidMain";
    }

    /**
     * 已付款主页
     */
    @RequestMapping("/paidMain")
    public String paidMain() {
        return "gtimp3/declaration/paidMain";
    }

    /**
     * 已驳回主页
     */
    @RequestMapping("/rejectMain")
    public String rejectMain() {
        return "gtimp3/declaration/rejectMain";
    }

    /**
     * 查询客户未付款单证
     */
    @RequestMapping("/findUnpaidList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("container_no"), @JField("contract_no"), @JField("bl_no"), @JField("declaration_type"),@JField("enter_page"),@JField("company_name"), @JField("supCompany.name"), @JField("ctime"), @JField("creator"), @JField("state")})
    public Page<Declaration> findUnpaidList(Jqgrid jqgrid) {
        if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
            String companyId = LoginUtil.getLoginUser().getCompany().getId();
            jqgrid.addRule(new SearchRule("customer.id", SearchRuleOption.eq, companyId));
        }
        jqgrid.addRule(new SearchRule("payment_type", SearchRuleOption.eq, "0"));
        // jqgrid.addRule(new SearchRule("state", SearchRuleOption.in,
        // Declaration.DeclarationBusinessState.DRAFT_STATE)
        try {
            return declarationBiz.findByJqgrid(jqgrid);
        } catch (Exception e) {
            logger.error("DeclarationAction.findUnpaidList.[jqgrid=" + jqgrid + "]查询单证错误！");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询客户已付款单证
     */
    @RequestMapping("/findPaidList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("container_no"), @JField("contract_no"),@JField("enter_page"), @JField("company_name"), @JField("supCompany.name"), @JField("declaration_port"), @JField("confirmTime"), @JField("creator"), @JField("validator.name"), @JField("state"), @JField("evaluation.evalId"), @JField("evaluation.evaluationRecords"), @JField("diDans.id"), @JField("declaration_type"), @JField("sno"), @JField("export_port")})
    public Page<Declaration> findPaidList(Jqgrid jqgrid) {
        if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
            String companyId = LoginUtil.getLoginUser().getCompany().getId();
            jqgrid.addRule(new SearchRule("customer.id", SearchRuleOption.eq, companyId));
        }
        List<String> paymentTypes = new ArrayList<>();
        paymentTypes.add("1");
        paymentTypes.add("2");
        jqgrid.addRule(new SearchRule("payment_type", SearchRuleOption.in,  paymentTypes));
        List<String> stateList = new ArrayList<>();
        stateList.add(Declaration.DeclarationBusinessState.DRAFT_STATE);
        stateList.add(Declaration.DeclarationBusinessState.REJECT_STATE);
        stateList.add(Declaration.DeclarationBusinessState.REJECT_WAIT_REDIT_STATE);
        jqgrid.addRule(new SearchRule("state", SearchRuleOption.ni, stateList));
        try {
            Page<Declaration> declarationPage = declarationBiz.findByJqgrid(jqgrid);
            return declarationPage;
        } catch (Exception e) {
            logger.error("DeclarationAction.findPaidList.[jqgrid=" + jqgrid + "]查询单证错误！");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询已驳回单证
     */
    @RequestMapping("/findRejectList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("container_no"), @JField("contract_no"),@JField("enter_page"), @JField("company_name"), @JField("supCompany.name"), @JField("confirmTime"), @JField("creator"), @JField("validator.name"), @JField("rejectContent.rejectDate"), @JField("rejectContent.rejectPerson"), @JField("rejectContent.content"), @JField("declaration_type")})
    public Page<Declaration> findRejectList(Jqgrid jqgrid) {
        if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
            String companyId = LoginUtil.getLoginUser().getCompany().getId();
            jqgrid.addRule(new SearchRule("customer.id", SearchRuleOption.eq, companyId));
        }
        jqgrid.addRule(new SearchRule("state", SearchRuleOption.eq, Declaration.DeclarationBusinessState.REJECT_STATE));
        try {
            Page<Declaration> declarationPage = declarationBiz.findByJqgrid(jqgrid);
            return declarationPage;
        } catch (QueryException e) {
            logger.error("DeclarationAction.findRejectList.[jqgrid=" + jqgrid + "]查询单证错误！");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据主键id删除未付款单证
     */
    @RequestMapping("/deleteUnpaidDeclaration")
    @ResponseBody
    public Result deleteUnpaidDeclaration(String id) {
        if (StringUtils.isNotEmpty(id)) {
            try {
                Declaration declaration = declarationBiz.findEntityById(id);
                if (declaration != null) {
                    String paymengType = declaration.getPayment_type();
                    String state = declaration.getState();
                    if (StringUtils.isNotEmpty(paymengType) && paymengType.equals("0") || (StringUtils.isNotEmpty(state) && state.equalsIgnoreCase(Declaration.DeclarationBusinessState.REJECT_WAIT_REDIT_STATE))) {
                        declarationBiz.delete(declaration);
                        return Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
                    }
                }
            } catch (Exception e) {
                logger.error("DeclarationAction.deleteDeclaration.[id=" + id + "]删除单证错误！");
                e.printStackTrace();
            }
        }
        return Result.newFailInstance(MsgConstants.DEL_FAIL);
    }

    /**
     * 查验->选择查验商品
     */
    @RequestMapping("/gotoSelectPage")
    public String gotoSelectPage(Model model, String declarationId) {
        if (StringUtils.isNotEmpty(declarationId)) {
            model.addAttribute("declarationId", declarationId);
        }
        return "gtimp3/declaration/toSelect";
    }

    // 根据主键id查询未付款单证
    public Declaration findUnpaidDeclaration(String id, Model model) {
        if (StringUtils.isNotEmpty(id)) {
            try {
                Declaration declaration = declarationBiz.findEntityById(id);
                model.addAttribute("declaration", declaration); // 未付款单证
                // PackingListDetailed packingdet =
                // packingListDetailedBiz.findCommdetailByid(declaration.getId());
                // Commodity commodity=new Commodity();
                // model.addAttribute("packingdet", packingdet); //商品明细装箱单
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据主键id查询未付款单证 出口
     */
    @RequestMapping("/findUnpaidDeclarationExport")
    public String findUnpaidDeclarationExport(@RequestParam(required = false) String table, String id, Model model) {
        try {
            findUnpaidDeclaration(id, model);
            model.addAttribute("table", table);
            return OrderAction.ORDER_DECLARE_PAGE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据主键id查询未付款单证 进口
     */
    @RequestMapping("/findUnpaidDeclarationEntry")
    public String findUnpaidDeclarationEntry(@RequestParam(required = false) String table, String id, Model model) {
        try {
            model.addAttribute("table", table);
            findUnpaidDeclaration(id, model);
            return OrderAction.ORDER_DECLARE_PAGE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转关设置界面
     */
    @RequestMapping("/declaration-toZhuanGuan")
    public String toZhuanGuan() {
        return "/gtimp/declaration/toZhuanGuan";
    }

    @RequestMapping("/declaration-doUpdateQptyno")
    @ResponseBody
    public Result updateQptyno(Declaration declaration) {
        List<String> properties = new ArrayList<String>();
        if (declaration != null && jedisClientCluster.get("lock_decla_" + declaration.getId(), String.class) != null) {
            return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
        }
        properties.add("qptyno");
        try {
            declarationBiz.updateEntity(declaration, properties);
        } catch (SaveException e) {
            logger.error(e.getMessage());
            return Result.newSuccessInstance("操作失败");
        }
        return Result.newSuccessInstance("操作成功");
    }

    /**
     * 同步QP数据
     */
    @RequestMapping("/declaration-syncQPData")
    @ResponseBody
    public Result syncQPData(String did, String fu) {
        try {
            return declarationBiz.syncQPData(did, fu);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            dataLockUtil.releaseLock("VDBS", did);
            return Result.newFailInstance("操作失败");
        }
    }

    @Resource
    private ContractTermsBiz contractTermsBiz;

    @RequestMapping("/saveContract")
    @ResponseBody
    public Result saveContract(ContractTerms contractTerms, String contract_remark, String declarationId, String contract_terms_type) {
        if (StringUtils.isNotEmpty(declarationId)) {
            try {
                Declaration declaration = declarationBiz.findEntityById(declarationId);
                if (declaration != null) {
                    ContractTerms temp = contractTermsBiz.findEntityByDeclaration(declaration);
                    if (temp != null && StringUtils.isNotEmpty(temp.getId())) {
                        contractTerms.setId(temp.getId());
                    } else {
                        contractTerms.setId(null);
                    }
                    contractTerms.setDeclaration(declaration);
                    contractTermsBiz.saveOrupdateEntity(contractTerms);
                    declaration.setContract_remark(contract_remark);
                    declaration.setContract_terms_type(contract_terms_type);
                    declaration.setContractTerms(contractTerms);
                    declarationBiz.saveOrupdateEntity(declaration);
                    return Result.newSuccessInstance("操作成功");

                }
            } catch (QueryException e) {
                e.printStackTrace();
            } catch (SaveException e) {
                e.printStackTrace();
            }
        }

        return Result.newFailInstance("操作失败");
    }

    /**
     * 上传到单一窗口申报系统
     *
     * @return 上传结果 成功还是失败
     */
    @RequestMapping("/up2cargoDecla")
    @ResponseBody
    public Result uploadToCargoDeclaration(String declarationId, String wayCode) {
        if (jedisClientCluster.get("lock_decla_" + declarationId, String.class) != null) {
            return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
        }
        try {
            if (ComDeclaWay.WayCodeEnum.GZ_PORT_HTTPS.toString().equals(wayCode)) {
                declarationBiz.uploadToCargoDeclaration(declarationId);
            } else if (ComDeclaWay.WayCodeEnum.COM_PORT_FTP.toString().equals(wayCode)) {
                singleWindow.up2cargoDecla(declarationId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.newFailInstance("操作失败：" + e.getMessage());
        }
        return Result.newSuccessInstance("操作成功");
    }

    /**
     * 跳转到选择二级供应商
     *
     * @author han
     */
    @RequestMapping("/selSecondSup")
    public String selSecondSup(HttpServletRequest reqeust) {
        reqeust.setAttribute("code", reqeust.getParameter("code"));
        return "gtimp3/declaration/secondSup";
    }

    /**
     * 从单一窗口申报系统更新状态
     *
     * @return 更新结果 成功还是失败
     */
    // @RequestMapping("/updateCargoDeclaStatus")
    // @ResponseBody
    // public Result updateCargoDeclaStatus(String declarationId){
    // try {
    // declarationBiz.updateCargoDeclaStatus(declarationId);
    // } catch (Exception e) {
    // e.printStackTrace();
    // return Result.newFailInstance("更新失败：" + e.getMessage());
    // }
    // return Result.newSuccessInstance("更新成功");
    // }

    @Autowired
    private JedisClientClusterImpl jedisClientCluster;

    @RequestMapping("/validateGoodsCodeCache")
    @ResponseBody
    public int validateGoodsCodeCache(String record) {
        if (StringUtils.isEmpty(record)) {
            return 0;
        }
        JSONObject recordObject = JSONObject.fromObject(record);
        if (recordObject != null) {
            String code_t = recordObject.get("code_t").toString();
            String code_s = recordObject.get("code_s").toString();
            String count = recordObject.get("count").toString();
            String legal_count = recordObject.get("legal_count").toString();
            String unit_price = recordObject.get("unit_price").toString();
            List<Map<String, Object>> list = jedisClientCluster.range("goodsCode", 0, -1, Map.class);

            for (Map<String, Object> map : list) {
                Object object = map.get(code_t + code_s);
                if (object != null) {
                    JSONObject jsonObject = JSONObject.fromObject(object);
                    String UNITPRICE_MIN = jsonObject.get("UNITPRICE_MIN").toString();
                    String UNITPRICE_MAX = jsonObject.get("UNITPRICE_MAX").toString();
                    String QR_MX = jsonObject.get("QR_MX").toString();
                    String QR_MIN = jsonObject.get("QR_MIN").toString();
                    System.out.println(UNITPRICE_MIN + "-" + UNITPRICE_MAX + "-" + QR_MX + "-" + QR_MIN);
                    float _count = Float.parseFloat(count);
                    float _legal_count = Float.parseFloat(legal_count);
                    float qr = _count / _legal_count;

                    String result = "";
                    if (qr > Float.parseFloat(QR_MX)) {
                        // System.out.println("大于最大值");
                        result += "1";
                    } else if (qr < Float.parseFloat(QR_MIN)) {
                        // System.out.println("小于最小值");
                        result += "2";
                    }
                    if (Float.parseFloat(unit_price) > Float.parseFloat(UNITPRICE_MAX)) {
                        // System.out.println("单价大于最大值");
                        result += "3";
                    } else if (Float.parseFloat(unit_price) < Float.parseFloat(UNITPRICE_MIN)) {
                        // System.out.println("单价小于最小值");
                        result += "4";
                    }
                    if (StringUtils.isEmpty(result)) {
                        result = "0";
                    }
                    return Integer.parseInt(result);
                }
            }
        }
        return 0;
    }

    /**
     * 二级供应商补资料首页
     *
     * @author han
     */
    @RequestMapping("/secondSupMain")
    public String secondSupMain() {
        return "gtimp3/declaration/secondSupMain";
    }

    /**
     * 查询供应商待上传附件单证
     *
     * @author han
     */
    @RequestMapping("/findSecondSupValidList")
    @ResponseBody
    @Json({@JField("id"), @JField("businessId"), @JField("container_no"), @JField("bl_no"), @JField("declaration_type"),@JField("enter_page"), @JField("contract_no"), @JField("company_name"), @JField("customer.name"), @JField("declaration_port"), @JField("confirmTime"), @JField("creator"), @JField("validator.name"), @JField("uploadDiDan.name"), @JField("state"), @JField("paymentTime"), @JField("data_type")})
    public Page<Declaration> findSecondSupValidList(Jqgrid jqgrid, HttpServletResponse response) {
        String companyId = LoginUtil.getLoginUser().getCompany().getId();
        jqgrid.addRule(new SearchRule("isTongguanYth", SearchRuleOption.eq, "1"));
        jqgrid.addRule(new SearchRule("secondSupIdCode", SearchRuleOption.eq, companyId));
        Filter filters = jqgrid.getFilters();
        List<String> stateList = new ArrayList<String>();
        stateList.add(Declaration.DeclarationBusinessState.PASS_STATE);
        stateList.add(Declaration.DeclarationBusinessState.ACCEPT_STATE);
        stateList.add(Declaration.DeclarationBusinessState.COMPLETE_STATE);
        stateList.add(Declaration.DeclarationBusinessState.FIR_PASS);
        stateList.add(Declaration.DeclarationBusinessState.SEC_PAS);
        stateList.add(Declaration.DeclarationBusinessState.SCENE_SUBMIT);
        stateList.add(Declaration.DeclarationBusinessState.CUSTOM_CHECK);
        stateList.add(Declaration.DeclarationBusinessState.CUSTOM_PASS);
        SearchRule stateRule = new SearchRule("state", SearchRuleOption.in, stateList);
        filters.addRule(stateRule);

        jqgrid.addRule(new SearchRule("payment_type", SearchRuleOption.eq, "1"));
        jqgrid.addOrder(Sort.Direction.ASC, "paymentTime");
        try {
            Page<Declaration> declarationPage = declarationBiz.findByJqgrid(jqgrid);
            return declarationPage;
            // JsonBinder builder = JsonBinder.buildNormalBinder();
            // builder.setDateFormat("yyyy-MM-dd HH:mm:ss");
            // ResponseUtils.renderText(response, builder.toJson(declarationPage));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转关设置界面
     */
    @RequestMapping("/declaration-toZhuanGuanNoQp")
    public String toZhuanGuanNoQp() {
        return "/gtimp/declaration/toZhuanGuanNoQp";
    }

    @Resource
    SingleWindow singleWindow;

    @RequestMapping("/buildxml")
    public Result fasjll(String did) throws Exception {
        singleWindow.buildXML(did);
        System.out.println(System.getProperty("catalina.home"));
        return Result.newSuccessInstance("操作完成");
    }

    /**
     * 上传到单一窗口申报系统
     *
     * @return 上传结果 成功还是失败
     */
    @RequestMapping("/parseAllSWClientReceipt")
    @ResponseBody
    public Result parseAllSWClientReceipt() {
        singleWindow.parseAllSWClentReceiptFile();
        return Result.newSuccessInstance("操作成功");
    }

    /**
     * 批量获取驳船信息
     *
     * @param ids 报关单id,用逗号分隔
     */
    @RequestMapping("/getShipInfos")
    @ResponseBody
    public Result getShipInfos(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return Result.newFailInstance("请选择需要操作的记录！");
        } else {
            return declarationBiz.getShipInfos(ids.split(","));
        }
    }

    /**
     * 获取联系方式
     */
    @RequestMapping("/getContactWay")
    @ResponseBody
    public Result getContactWay(String did, String role) {
        if (StringUtils.isNotEmpty(did) && StringUtils.isNotEmpty(role)) {
            return declarationBiz.getContactWay(did, role);
        }
        return Result.newFailInstance("参数传入错误");
    }
}
